<%--
  Created by IntelliJ IDEA.
  User: zhush
  Date: 2025/8/15
  Time: 20:38
  To change this template use File | Settings | File Templates.
--%>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<jsp:include page="header.jsp"/>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生考试成绩分析</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        /* 样式保持不变 */
        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .dashboard-header {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            color: white;
            padding: 1.5rem 0;
            border-radius: 0 0 15px 15px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            margin-bottom: 2rem;
        }
        .card {
            border-radius: 12px;
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.08);
            border: none;
            transition: transform 0.3s ease;
            margin-bottom: 1.5rem;
        }
        .card:hover {
            transform: translateY(-5px);
        }
        .card-header {
            background-color: #fff;
            border-bottom: 1px solid #eaeaea;
            font-weight: 600;
            padding: 1rem 1.5rem;
            border-radius: 12px 12px 0 0 !important;
        }
        .stat-card {
            text-align: center;
            padding: 1.5rem;
        }
        .stat-value {
            font-size: 2.2rem;
            font-weight: 700;
            margin: 0.5rem 0;
        }
        .stat-label {
            font-size: 0.9rem;
            color: #6c757d;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        .chart-container {
            position: relative;
            height: 400px;
            padding: 1rem;
        }
        .exam-table {
            font-size: 0.9rem;
        }
        .exam-table th {
            background-color: #f1f5fd;
            font-weight: 600;
        }
        .pass-rate {
            font-size: 1.8rem;
            font-weight: 700;
            color: #28a745;
        }
        .theory-color {
            color: #4e73df;
        }
        .practice-color {
            color: #1cc88a;
        }
        .legend-item {
            display: inline-block;
            margin-right: 1.5rem;
            font-size: 0.9rem;
        }
        .color-box {
            display: inline-block;
            width: 12px;
            height: 12px;
            margin-right: 5px;
            border-radius: 2px;
        }
        .student-info {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            border-radius: 10px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }
        .badge-pass {
            background-color: #28a745;
        }
        .badge-fail {
            background-color: #dc3545;
        }
        .pagination-container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 1rem;
        }
        .page-info {
            color: #6c757d;
            font-size: 0.9rem;
        }
        .table-container {
            max-height: 400px;
            overflow-y: auto;
        }
        .page-link {
            color: #4e73df;
            border: 1px solid #dee2e6;
            cursor: pointer;
        }
        .page-item.active .page-link {
            background-color: #4e73df;
            border-color: #4e73df;
            color: white;
        }
        .search-box {
            max-width: 300px;
        }
        .page-item.disabled .page-link {
            cursor: not-allowed;
            opacity: 0.6;
        }
        .loading {
            text-align: center;
            padding: 2rem;
            color: #6c757d;
        }
    </style>
</head>
<body>
<!-- 页面结构 -->
<div class="dashboard-header">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-md-8">
                <h1 class="display-5 fw-bold">学生考试成绩分析系统</h1>
                <p class="lead mb-0">跟踪学生理论成绩与实践成绩的变化趋势</p>
            </div>
            <div class="col-md-4 text-md-end">
                <div class="student-info">
                    <h5 class="mb-1">
                        <c:choose>
                            <c:when test="${not empty records[0].stuName}">
                                ${records[0].stuName}
                            </c:when>
                            <c:otherwise>
                                未知用户
                            </c:otherwise>
                        </c:choose>
                    </h5>
                    <p class="mb-1">
                        学号:
                        <c:choose>
                            <c:when test="${not empty records[0].idCard}">
                                S${records[0].idCard}
                            </c:when>
                            <c:otherwise>
                                未知
                            </c:otherwise>
                        </c:choose>
                        | 班级:
                        <c:choose>
                            <c:when test="${not empty records[0].className}">
                                ${records[0].className}
                            </c:when>
                            <c:otherwise>
                                未知班级
                            </c:otherwise>
                        </c:choose>
                    </p>
                    <small>最后更新: <span id="lastUpdateTime"></span></small>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="container">
    <!-- 统计卡片 -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card">
                <div class="stat-card">
                    <div class="stat-label">平均理论成绩</div>
                    <div class="stat-value theory-color" id="avgTheoryScore">--</div>
                    <small>满分: 100分</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card">
                <div class="stat-card">
                    <div class="stat-label">平均实践成绩</div>
                    <div class="stat-value practice-color" id="avgPracticeScore">--</div>
                    <small>满分: 100分</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card">
                <div class="stat-card">
                    <div class="stat-label">理论及格率</div>
                    <div class="stat-value text-success" id="theoryPassRate">--%</div>
                    <small>及格线: 60分</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card">
                <div class="stat-card">
                    <div class="stat-label">实践及格率</div>
                    <div class="stat-value text-success" id="practicePassRate">--%</div>
                    <small>及格线: 60分</small>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-8">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <span>考试成绩趋势分析</span>
                    <div class="legend">
                        <span class="legend-item"><span class="color-box" style="background-color: #4e73df;"></span>理论成绩</span>
                        <span class="legend-item"><span class="color-box" style="background-color: #1cc88a;"></span>实践成绩</span>
                    </div>
                </div>
                <div class="chart-container">
                    <canvas id="scoreChart"></canvas>
                </div>
            </div>
        </div>
        <div class="col-lg-4">
            <div class="card">
                <div class="card-header">及格率统计</div>
                <div class="chart-container">
                    <canvas id="passRateChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- 考试记录表格 -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <span>详细考试记录</span>
                    <div class="search-box">
                        <input type="text" class="form-control form-control-sm" id="searchInput" placeholder="搜索考试名称...">
                    </div>
                </div>
                <div class="card-body p-0">
                    <div id="loadingMessage" class="loading" style="display: none;">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                        <p class="mt-2">正在加载考试记录...</p>
                    </div>
                    <div class="table-responsive" id="tableContainer">
                        <table class="table table-hover exam-table mb-0">
                            <thead>
                            <tr>
                                <th>序号</th>
                                <th>考试名称</th>
                                <th>考试科目</th>
                                <th>考试日期</th>
                                <th>理论成绩</th>
                                <th>实践成绩</th>
                                <th>总分</th>
                                <th>考试结果</th>
                            </tr>
                            </thead>
                            <tbody id="examTableBody">
                            <!-- 数据通过JSTL直接渲染 -->
                            <c:forEach items="${records}" var="record" varStatus="status">
                                <tr>
                                    <td>${status.index + 1}</td>
                                    <td>${record.examName}</td>
                                    <td>
                                        <c:choose>
                                            <c:when test="${not empty record.courseName}">
                                                ${record.courseName}
                                            </c:when>
                                            <c:when test="${not empty record.className}">
                                                ${record.className}
                                            </c:when>
                                            <c:otherwise>
                                                -
                                            </c:otherwise>
                                        </c:choose>
                                    </td>
                                    <td>
                                        <fmt:formatDate value="${record.startTime}" pattern="yyyy-MM-dd"/>
                                    </td>
                                    <td class="theory-color">${record.theoryScore}</td>
                                    <td class="practice-color">${record.practiceScore}</td>
                                    <td>
                                        <fmt:formatNumber value="${record.theoryScore * 0.6 + record.practiceScore * 0.4}"
                                                          pattern="#0.0" />
                                    </td>
                                    <td>
                                        <span class="badge ${record.examResult ? 'bg-success' : 'bg-danger'}">
                                                ${record.examResult ? '通过' : '未通过'}
                                        </span>
                                    </td>
                                </tr>
                            </c:forEach>
                            </tbody>
                        </table>
                    </div>

                    <!-- 无数据提示 -->
                    <c:if test="${empty records}">
                        <div id="noDataMessage" class="loading">
                            <p>暂无考试记录</p>
                        </div>
                    </c:if>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // 全局变量
    let scoreChart = null;
    let passRateChart = null;

    // 页面加载完成后执行
    document.addEventListener('DOMContentLoaded', function() {
        // 设置最后更新时间
        document.getElementById('lastUpdateTime').textContent = new Date().toLocaleString();

        // 初始化页面数据
        initializePageWithJSTLData();
    });

    // 使用JSTL数据初始化页面
    function initializePageWithJSTLData() {
        <c:if test="${not empty records}">
        // 准备图表数据
        const examNames = [
            <c:forEach items="${records}" var="record" varStatus="status">
            '${record.examName}'<c:if test="${!status.last}">,</c:if>
            </c:forEach>
        ];

        const theoryScores = [
            <c:forEach items="${records}" var="record" varStatus="status">
            ${record.theoryScore}<c:if test="${!status.last}">,</c:if>
            </c:forEach>
        ];

        const practiceScores = [
            <c:forEach items="${records}" var="record" varStatus="status">
            ${record.practiceScore}<c:if test="${!status.last}">,</c:if>
            </c:forEach>
        ];

        // 计算统计数据
        const stats = calculateStatistics(theoryScores, practiceScores);

        // 更新统计卡片
        updateStatsCards(stats);

        // 初始化图表
        initializeCharts(examNames, theoryScores, practiceScores, stats);
        </c:if>

        <c:if test="${empty records}">
        // 无数据时隐藏表格容器
        document.getElementById('tableContainer').style.display = 'none';
        </c:if>
    }

    // 计算统计数据
    function calculateStatistics(theoryScores, practiceScores) {
        if (theoryScores.length === 0) return {};

        const avgTheory = theoryScores.reduce((a, b) => a + b, 0) / theoryScores.length;
        const avgPractice = practiceScores.reduce((a, b) => a + b, 0) / practiceScores.length;

        const theoryPassCount = theoryScores.filter(score => score >= 60).length;
        const practicePassCount = practiceScores.filter(score => score >= 60).length;

        const theoryPassRate = (theoryPassCount / theoryScores.length * 100).toFixed(1);
        const practicePassRate = (practicePassCount / practiceScores.length * 100).toFixed(1);

        return {
            avgTheory: avgTheory.toFixed(1),
            avgPractice: avgPractice.toFixed(1),
            theoryPassRate: theoryPassRate,
            practicePassRate: practicePassRate,
            theoryPassCount: theoryPassCount,
            practicePassCount: practicePassCount,
            totalExams: theoryScores.length
        };
    }

    // 更新统计卡片
    function updateStatsCards(stats) {
        document.getElementById('avgTheoryScore').textContent = stats.avgTheory;
        document.getElementById('avgPracticeScore').textContent = stats.avgPractice;
        document.getElementById('theoryPassRate').textContent = stats.theoryPassRate + '%';
        document.getElementById('practicePassRate').textContent = stats.practicePassRate + '%';
    }

    // 初始化图表
    function initializeCharts(examNames, theoryScores, practiceScores, stats) {
        // 销毁旧图表（如果存在）
        if (scoreChart) {
            scoreChart.destroy();
        }
        if (passRateChart) {
            passRateChart.destroy();
        }

        // 创建折线图
        const scoreCtx = document.getElementById('scoreChart').getContext('2d');
        scoreChart = new Chart(scoreCtx, {
            type: 'line',
            data: {
                labels: examNames,
                datasets: [
                    {
                        label: '理论成绩',
                        data: theoryScores,
                        borderColor: '#4e73df',
                        backgroundColor: 'rgba(78, 115, 223, 0.1)',
                        borderWidth: 3,
                        pointBackgroundColor: '#4e73df',
                        pointRadius: 5,
                        pointHoverRadius: 8,
                        tension: 0.3,
                        fill: true
                    },
                    {
                        label: '实践成绩',
                        data: practiceScores,
                        borderColor: '#1cc88a',
                        backgroundColor: 'rgba(28, 200, 138, 0.1)',
                        borderWidth: 3,
                        pointBackgroundColor: '#1cc88a',
                        pointRadius: 5,
                        pointHoverRadius: 8,
                        tension: 0.3,
                        fill: true
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false,
                        callbacks: {
                            label: function(context) {
                                return context.dataset.label + ': ' + context.parsed.y + '分';
                            }
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: false,
                        min: Math.min(...theoryScores, ...practiceScores) - 5,
                        max: 100,
                        title: {
                            display: true,
                            text: '成绩 (分)'
                        },
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)'
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        },
                        ticks: {
                            maxRotation: 45,
                            minRotation: 45
                        }
                    }
                }
            }
        });

        // 创建及格率饼图
        const theoryPassRate = parseFloat(stats.theoryPassRate);
        const practicePassRate = parseFloat(stats.practicePassRate);

        const passRateCtx = document.getElementById('passRateChart').getContext('2d');
        passRateChart = new Chart(passRateCtx, {
            type: 'doughnut',
            data: {
                labels: ['理论及格', '理论不及格', '实践及格', '实践不及格'],
                datasets: [{
                    data: [
                        theoryPassRate,
                        100 - theoryPassRate,
                        practicePassRate,
                        100 - practicePassRate
                    ],
                    backgroundColor: [
                        'rgba(78, 115, 223, 0.8)',
                        'rgba(78, 115, 223, 0.3)',
                        'rgba(28, 200, 138, 0.8)',
                        'rgba(28, 200, 138, 0.3)'
                    ],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            padding: 20,
                            usePointStyle: true
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return context.label + ': ' + context.parsed + '%';
                            }
                        }
                    }
                },
                cutout: '70%'
            }
        });
    }

    // 搜索功能（客户端搜索）
    document.getElementById('searchInput').addEventListener('input', function(e) {
        const searchTerm = e.target.value.toLowerCase();
        const rows = document.querySelectorAll('#examTableBody tr');

        rows.forEach(row => {
            const examName = row.cells[1].textContent.toLowerCase();
            const subjectName = row.cells[2].textContent.toLowerCase();

            if (examName.includes(searchTerm) || subjectName.includes(searchTerm)) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
    });
</script>
</body>
<jsp:include page="footer.jsp"/>